import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @Author: zyf
 * @Date: 2024/04/25/15:09
 * @Description:
 */
public class CommandExecutor {

    private final Map<String, String> env = System.getenv();

    private static final String osName = System.getProperty("os.name").toLowerCase();


    public static Result execOne(String command) throws IOException, InterruptedException {
        ProcessBuilder processBuilder = new ProcessBuilder();
        // 在构建器中设置命令和参数
        if (osName.contains("linux")) {
            // 如果是 linux
            processBuilder.command("bash", "-c", command);
        } else if (osName.contains("windows")) {
            // C:\Windows\system32\
            processBuilder.command("cmd.exe", "/c", command);
            processBuilder.directory(new File(System.getProperty("user.home")));
        }

        // 启动进程
        Process process = processBuilder.start();

        // 获取进程的输出流
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));

        // 读取输出
        StringBuilder output = new StringBuilder();
        reader.lines().forEachOrdered(line -> output.append(line).append(";\n"));

        // 等待进程执行结束
        int exitCode = process.waitFor();

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("os", osName);
        result.put("exitCode", exitCode);
        result.put("output", output.toString());

        return Result.success("操作成功", result);
    }
}
